<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?php 
	
	$current_dbprefix = $this->db->dbprefix;
	$this->db->set_dbprefix('default_');
	
	$escortAgeRange = getEscortAgeRange();
	$minAge = 18;
	$maxAge = convertAgeFromTimeStamp($escortAgeRange['max_age']);
	
	$breastSizeRange = getBreastSizeRange();
	$min_size = $breastSizeRange['min_size'];
	$max_size = $breastSizeRange['max_size'];
	
	$priceRange = getPriceRange();
	$min_price = $priceRange['min_price'];
	$max_price = $priceRange['max_price'];
	
	$hairColorArray = getHairColorOptionData_ioc();
	$servicesDataArray = getServicesData_ioc();
	$languageArray = getLanguagesOfEscortsUsed();
	$measureOptionArray = getMeasureOptionData_ioc();
	$professionArray = getProfessionData_ioc();
	
	$escortCategoryId = getKeyOfArray( getSiteCategoryBaseOnSiteSetting() );	
	
	$page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0 ;
	$records_per_page = RECORD_PER_PAGE; 
	
    $agency_id = (isset($_GET['agency_id'])) ? intval($_GET['agency_id']) : 0;
     
	if(!isset($_GET['tm'])){
			
			$segment = $this->uri->segment(3,'');
			$fixedVar = false;
			if($segment){
				$linkArr = reDirectSite();
				if( in_array($segment,array_keys($linkArr)) ){
					$fixedVar = true;
				}
			}
			
			$listPackArray = array();
			foreach(getPackListData_ioc() as $key=>$arrayValue){
				$listPackArray[$key] = $arrayValue[0];
			}
			
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			$pre = array_keys(getCountriesOfEscortsUsed());
			$DEFAULT_COUNTRY = getCountryInfoFromUserGeoLocation();
			$preCountry = ($DEFAULT_COUNTRY) ? $DEFAULT_COUNTRY->getId() : $pre[0];
			$cityData = getCityInfoFromUserGeoLocation();
			
			$category_id = (isset($_GET['category_id'])) ? intval($_GET['category_id']) : $escortCategoryId;
			$country_id = (isset($_GET['country_id'])) ? intval($_GET['country_id']) : $preCountry;
			$state_id = (isset($_GET['state_id'])) ? intval($_GET['state_id']) : 0;//$cityData['state_id'];
			$province_id = (isset($_GET['province_id'])) ? intval($_GET['province_id']) : 0;
			$city_id = (isset($_GET['city_id'])) ? intval($_GET['city_id']) : 0;//$cityData['city_id'];
			$borncountry_id = (isset($_GET['borncountry_id'])) ? intval($_GET['borncountry_id']) :0;
			
			$state_province_city_id = (isset($_GET['state_province_city_id'])) ? $_GET['state_province_city_id'] : 'na';
			if($state_province_city_id != 'na' AND $state_province_city_id != -1){
				$epl = explode('|',$state_province_city_id);
				$state_id = isset($epl[0]) ? $epl[0]:0;
				$province_id = isset($epl[1]) ? $epl[1]:0;
				$city_id = isset($epl[2]) ? $epl[2]:0;
			}
			
			if($fixedVar){
				$country_id = $linkArr[$segment]['country_id'];
				$state_id = $linkArr[$segment]['state_id'];
				$province_id = $linkArr[$segment]['province_id'];
				$city_id = $linkArr[$segment]['city_id'];
			}
			
			$name = $this->input->get('name', '');
			
			//$mediaFormArray = isset($_GET['media']) ? array_filter($_GET['media']):array();
			$agentFormArray = isset($_GET['agent']) ? ($_GET['agent']):array();
			$hairFormArray = isset($_GET['hair_id']) ? array_filter($_GET['hair_id']):array();
			$servicesFormArray = isset($_GET['services']) ? array_filter($_GET['services']):array();
			$languagesFormArray = isset($_GET['language']) ? array_filter($_GET['language']):array();
			$professionFormArray = isset($_GET['profession']) ? array_filter($_GET['profession']): array() ;
			
			$from_age = isset($_GET['from_age']) ? intval($_GET['from_age']) : $minAge;
			$to_age = isset($_GET['to_age']) ? intval($_GET['to_age']) :$maxAge;
			
			$from_price = isset($_GET['from_price']) ? intval($_GET['from_price']) : $min_price;
			$to_price = isset($_GET['to_price']) ? intval($_GET['to_price']) : $max_price;
			
			$from_size = isset($_GET['from_size']) ? intval($_GET['from_size']) : $min_size;
			$to_size = isset($_GET['to_size']) ? intval($_GET['to_size']) : $max_size;
			
			$without_price = isset($_GET['without_price']) ? intval($_GET['without_price']) : 0;
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
			
			$independent = " 1 ";
			if($agentFormArray){
				if(in_array(0,$agentFormArray) AND in_array(1,$agentFormArray)){
					$independent = " 1 ";
				}else if(in_array(0,$agentFormArray) AND !in_array(1,$agentFormArray)){
					$independent = " A.permission_slug = '".USER_TYPE_ESCORT."' ";
				}else if( !in_array(0,$agentFormArray) AND in_array(1,$agentFormArray)){
					$independent = " A.permission_slug = '".USER_TYPE_AGENT."' ";
				}
			}
			
			if(strlen($name)){
				$nameCond = " ( B.escort_name LIKE '%".mysql_real_escape_string($name)."%' AND B.published=1 ) ";
			}else{
				$nameCond = " ( B.published=1 ) ";
			}
			
			$hairCond = " 1 ";
			if($hairFormArray){
				$tmpArr = array();
				foreach($hairFormArray as $id){
					$regexp = "[[:<:]]{$id}[[:>:]]";
					$tmpArr[] = " B.hair_color_id REGEXP '$regexp' " ; 
				}
				$hairCond = " (".implode(" OR ",$tmpArr).") ";
			}
			
			$mediaCond = " 1 ";
			/**
			if($mediaFormArray){
				$tmpArr = array();
				foreach($mediaFormArray as $id){
					$regexp = "[[:<:]]{$id}[[:>:]]";
					$tmpArr[] = " B.package_ids REGEXP '$regexp' " ; 
				}
				$mediaCond = " (".implode(" OR ",$tmpArr).") ";
			}
			**/
			
			$ageInt1 = time() - 31536000*$from_age; 
			$ageInt2 = time() - 31536000*$to_age; 
			$fromAge = min( array($ageInt1,$ageInt2));
			$toAge = max( array($ageInt1,$ageInt2));
			$ageCond = " (B.birth_date >= $fromAge AND B.birth_date <= $toAge) ";
			
			$breasts_penisCond = " (B.measure_1 >= $from_size AND B.measure_1 <= $to_size) ";
			
			$servicesCond = " 1 ";
			if($servicesFormArray){
				$tmpArr = array();
				
				foreach($servicesFormArray as $id){
					$regexp = "[[:<:]]{$id}[[:>:]]";
					$tmpArr[] = " B.service_ids REGEXP '$regexp' ";
				}
				$servicesCond = " (".implode(" OR ",$tmpArr).") ";
			}
			
			$languagesCond = " 1 ";
			if($languagesFormArray){
				$tmpArr = array();
				foreach($languagesFormArray as $id){
					$regexp = "[[:<:]]{$id}[[:>:]]";
					$tmpArr[] = " B.language_ids REGEXP '$regexp' ";
				}
				$languagesCond = " (".implode(" OR ",$tmpArr).") ";
			}
			
			$professionCond = " 1 ";
			if($professionFormArray){
				$tmpArr = array();
				foreach($professionFormArray as $id){
					//$regexp = "[[:<:]]{$id}[[:>:]]";
					//$tmpArr[] = " B.profession_id REGEXP '$regexp' ";
					$tmpArr[] = " B.profession_id = $id ";
				}
				$professionCond = " (".implode(" OR ",$tmpArr).") ";
			}
			
			/*
			$locationArr = array();
			$locationArr[] = ($country_id != 0) ? "B.country_id=$country_id" :'1';
			$locationArr[] = ($state_id != 0) ? "B.state_id=$state_id" :'1';
			$locationArr[] = ($province_id != 0) ? "B.province_id=$province_id" :'1';
			$locationArr[] = ($city_id != 0) ? "B.city_id=$city_id" :'1';
			
			$locationCond = " (".implode(' AND ',$locationArr).") ";
			*/
			$locationCond = 1;
			
			$listingArr = array();
			if($state_id == -1){
				$listingArr[] = ($country_id != 0) ? "country_id=$country_id" :'1';
				$listingCond = " (".implode(' AND ',$listingArr).") ";
			}else{
				$listingArr[] = ($country_id != 0) ? "country_id=$country_id" :'1';
				$listingArr[] = ($state_id != 0) ? "state_id=$state_id" :'1';
				$listingArr[] = ($province_id != 0) ? "province_id=$province_id" :'1';
				$listingArr[] = ($city_id != 0) ? "city_id=$city_id" :'1';
				$listingCond = " (".implode(' AND ',$listingArr).") ";
			}
			$rs = $this->db->query("SELECT * FROM ".TBL_PLACE_LIST." WHERE $listingCond")->result();
			 
			if($rs){
				$tmpArr = array();
				foreach($rs as $item){
					$regexp = "[[:<:]]{$item->id}[[:>:]]";
					$tmpArr[] = " B.places_list_ids_contract REGEXP '$regexp' ";
				}
				$listingPlaceCond = " (".implode(" OR ",$tmpArr).") ";
			}else{
				$listingPlaceCond = "1=0";
			}
			 
			$agent_cond = " 1 ";
			if($agency_id != 0 AND in_array(1,$agentFormArray)){
				$agent_cond = " A.id=$agency_id ";
			}
			
			$borncountry_cond = " 1 ";
			if($borncountry_id != 0){
				$borncountry_cond = " B.borncountry_id=$borncountry_id ";
			}
			
			$condition = $nameCond." AND ".$hairCond.
						" AND $ageCond AND $breasts_penisCond AND ".
						$servicesCond." AND ".$languagesCond.
						" AND ".$locationCond." AND ".$mediaCond." AND ".$independent." AND $listingPlaceCond AND $professionCond AND B.escort_category_id=$category_id AND $agent_cond AND $borncountry_cond";
			//$condition = 1;
			if($without_price == 0){
				$right_join = " INNER JOIN ".TBL_PRICING_TIME." AS C ON B.id=C.escort_id ";
				$right_join_cond = "AND (C.price >=$from_price AND C.price <= $to_price) ";
			}else{
				$right_join = '';
				$right_join_cond = '';
			}
			
			
			$query = "SELECT DISTINCT B.id AS escort_id FROM ".TBL_USER. //
						" AS A INNER JOIN ".TBL_ESCORT." AS B ON A.id=B.user_id $right_join WHERE $condition $right_join_cond ORDER BY order_value DESC";
						
			$allResult = $this->db->query($query)->result();
			$total = count( $allResult );
			
			//$queryURL = $_SERVER['QUERY_STRING'] ? '?'.$_SERVER['QUERY_STRING'] : '';
			$queryURL = "";
			$tmp = array();
			foreach($_GET as $item => $value){
				if($item != "per_page"){
					$tmp[] = "$item=$value";
				}
			}
			$queryURL = "?".implode("&",$tmp);
			
			if(! $fixedVar){
				$currentUrl = str_replace( 'per_page','per_page_'.$page, ("home/search_page".$queryURL) );
				$pagination = create_pagination( 
											$uri = $currentUrl, 
											$total_rows = $total , 
											$limit= $records_per_page,
											$uri_segment = 0,
											TRUE, TRUE 
										);
			}else{
				
				$pagination = create_pagination( 
											$uri = "search/$segment/?is_async=1", 
											$total_rows = $total , 
											$limit= $records_per_page,
											$uri_segment = 0,
											TRUE, TRUE 
										);
			}
			$records = $this->db->query($query." LIMIT ".$page." ,$records_per_page ;")->result();
	
	}
	
	if(isset($_GET['tm']) AND $_GET['tm'] == 'ag'){
			
		$user_id = intval($_GET['uid']);
		$rs =  $this->db->where(array('user_id'=>$user_id, 'service_type'=>'PLACE', 'payment_status'=>'paid', 'using_flag'=> 'yes'))
			->get(TBL_ESCORT_PAYMENT_LOG)->result();
		
		if($rs){
			$rs2 = $this->db->where('id',$rs[0]->type_id)->get(TBL_PLACE_LIST)->result();
			$listingPlaceCond = " 1 ";
			$country_id = $rs2[0]->country_id;
			$state_id = $rs2[0]->state_id;
			$province_id = $rs2[0]->province_id;
			$city_id = $rs2[0]->city_id;
		}else{
			$listingPlaceCond = "1=0";
		}
		
		$query = "SELECT DISTINCT id AS escort_id FROM ".TBL_ESCORT. 
				" WHERE published =1 AND $listingPlaceCond AND user_id=$user_id AND escort_category_id=$escortCategoryId ORDER BY order_value DESC";
 		 		
		$allResult = $this->db->query($query)->result();
		$total = count( $allResult );
		
		//$queryURL = $_SERVER['QUERY_STRING'] ? '?'.$_SERVER['QUERY_STRING'] : '';
		$queryURL = "";
		$tmp = array();
		foreach($_GET as $item => $value){
			if($item != "per_page"){
				$tmp[] = "$item=$value";
			}
		}
		$queryURL = "?".implode("&",$tmp);
		
		$currentUrl = str_replace( 'per_page','per_page_'.$page, ("home/search_page".$queryURL) );
		$pagination = create_pagination( 
									$uri = $currentUrl, 
									$total_rows = $total , 
									$limit= $records_per_page,
									$uri_segment = 0,
									TRUE, TRUE 
								);
		
		$records = $this->db->query($query." LIMIT ".$page." ,$records_per_page ;")->result();
	}
	
	$_SESSION['backURL'] = str_replace('search_page','search',fullURL() );
	
	$_SESSION['pagination_result'] = array();
	$i = 1;
	foreach($allResult as $item){
		$_SESSION['pagination_result'][$item->escort_id] = array( $i++ => $item->escort_id);
	}
	$_SESSION['totalRESULTsearch'] = $total;
	$_SESSION['location_ids'] = $country_id.'|'.$state_id.'|'.$province_id.'|'.$city_id;
	if(isset($_GET['df'])){
		unset($_SESSION['location_ids']);
	}
	
?>

<?php 
	$stringDesc = '';
	$location = $this->home_m->findLocationInfo();
	$sLoc = ($location['city'])?$location['city']:( ($location['province'])?$location['province']:(($location['state'])?:$location['country']));
	if($sLoc){
		$stringDesc = str_replace('$1',$sLoc,language_translate('search_escort_location_desc')); 
		
		breadcumb_reset();
		
		breadcumb(2,array(language_translate('breadcumb_search'), site_url_lang("home/search")));	
		if( $location['country'] AND $location['country_id'] != 0 ){	
			breadcumb(3, array($location['country'],
						site_url_lang("home/search?country_id=".$location['country_id'].'&state_id=-1')));
		}	
		
		if( $location['state'] AND $location['state_id'] != 0 ){	
			breadcumb(4, array($location['state'],
						site_url_lang("home/search?country_id=".$location['country_id'].'&state_id='.$location['state_id'])));
		}					
		if( $location['province'] AND $location['province_id'] != 0 ){				
			breadcumb(5, array($location['province'],
							site_url_lang("home/search?country_id=".$location['country_id'].'&state_id='.$location['state_id'].'&province_id='.$location['province_id'])
					)
				);
		}		
		if(  $location['city'] AND $location['city_id'] != 0 ){
			breadcumb(6, array( $location['city'],
							site_url_lang("home/search?country_id=".$location['country_id'].'&state_id='.$location['state_id'].'&province_id='.$location['province_id'].'&city_id='.$location['city_id'])
					)
				); 	
		}
		
		echo breadcumb_html();
	}elseif(isset($_GET['tm']) AND $_GET['tm'] == 'ag'){
		$user_id = intval($_GET['uid']);
		$U = $this->user_entity->init('id',$user_id);
		$stringDesc = str_replace('$1',$U->getName(),language_translate('search_escort_of_agent_desc')); 
		
		//change breadcumb
		breadcumb_reset();
		
		breadcumb(2,array(language_translate('breadcumb_search'), site_url_lang("home/search")));	
		breadcumb(3,array(language_translate('breadcumb_agent'), site_url_lang("home/search")));
		breadcumb(4,array($U->getName(), site_url_lang("home/search/?tm=ag&uid=$user_id")));
		echo breadcumb_html();
	}	
	
	if($agency_id != 0 AND in_array(1,$agentFormArray)){
		$U = $this->user_entity->init('id',$agency_id);
		$stringDesc = str_replace('$1',$U->getName(),language_translate('search_escort_of_agent_desc')); 
		
		//change breadcumb
		breadcumb_reset();
		
		breadcumb(2,array(language_translate('breadcumb_search'), site_url_lang("home/search")));	
		breadcumb(3,array(language_translate('breadcumb_agent'), site_url_lang("home/search")));
		breadcumb(4,array($U->getName(), site_url_lang("home/search/?tm=ag&uid=$agency_id")));
		echo breadcumb_html();
	}
	 
?>

<?php $this->db->set_dbprefix($current_dbprefix);?>


	<div class="search-escort-list">
		<?php $this->load->view("home/display_escort_info", array('records'=>$records,'item_per_row'=>3,'page'=>'SEARCH') ) ;?>
		
		<div class="clear"></div>
		<div class="pagging">
			<div id="search_escort">
				<?php echo $pagination['links'];?>
			</div>
		</div>
	</div>
	<div class="clear"></div>
	
<script type="text/javascript">
	var TOTAL_RESULTS = <?php echo $total;?>;
	/* var COND = "<?php  //echo $query;?>";*/	
	$(document).ready(function(){
		var desc = '<?php echo $stringDesc;?>';
		if(desc != ''){
			$('#search-desc').show().html(desc);
		}
	});
</script>